﻿using MyModule.ManageSheep;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace MyModule.Breeding
{
    public class BodySizeService : ApplicationService, IBodySizeService
    {

        private readonly IRepository<BodySize, int> _weighInfoRepository;
        private readonly IRepository<VarietyInfo, int> _varietyInfoRepository;
        private readonly IHttpClientFactory _httpClientFactory;

        public BodySizeService(IRepository<BodySize, int> weighInfoRepository, IRepository<VarietyInfo, int> varietyInfoRepository, IHttpClientFactory httpClientFactory)
        {
            _weighInfoRepository = weighInfoRepository;
            _varietyInfoRepository = varietyInfoRepository;
            _httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="bodySizeDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<BodySizeDTO>> CreateAsync(BodySizeDTO bodySizeDTO)
        {
            var list = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Earbugles == bodySizeDTO.Earbugles);
            if (list == null)
            {
                BodySize bodySize = new BodySize();
            bodySize.Bdate = bodySizeDTO.Bdate;
            bodySize.Bbuildings = bodySizeDTO.Bbuildings;
            bodySize.Bcolumns = bodySizeDTO.Bcolumns;
            bodySize.Vid = bodySizeDTO.Vid;
            bodySize.Bsex = bodySizeDTO.Bsex;
            bodySize.Earbugles = bodySizeDTO.Earbugles;
            bodySize.Bheight = bodySizeDTO.Bheight;
            bodySize.Blength = bodySizeDTO.Blength;
            bodySize.Bust = bodySizeDTO.Bust;
            bodySize.Bpipe = bodySizeDTO.Bpipe;
            bodySize.Bscrotal = bodySizeDTO.Bscrotal;
            bodySize.Bthickness = bodySizeDTO.Bthickness;
            bodySize.Barea = bodySizeDTO.Barea;
            bodySize.Bwidth = bodySizeDTO.Bwidth;
            var result = await _weighInfoRepository.InsertAsync(bodySize);
            var listCount = ObjectMapper.Map<BodySize, BodySizeDTO>(result);
                if (listCount != null)
                {
                    return new ResultDto<BodySizeDTO>() { Code = 200, Message = "添加成功" };
                }
                else
                {
                    return new ResultDto<BodySizeDTO>() { Code = 500, Message = "添加失败" };
                }
            }
            else
            {
                return new ResultDto<BodySizeDTO>() { Code = 501};
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Bid"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int Bid)
        {
            await _weighInfoRepository.DeleteAsync(Bid);
        }
        /// <summary>
        /// 显示分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<BodySizeVarietyDTO>> GetBasListAsync(int Vid,string? Earbugles)
        {
            var result = await _weighInfoRepository.GetListAsync();
            var varietie = await _varietyInfoRepository.GetListAsync();
            var list = (from a in result
                        join b in varietie on a.Vid equals b.Id
                        select new BodySizeVarietyDTO
                        {
                            Id = a.Id,
                            Vname = b.Vname, 
                            Bdate = a.Bdate,
                            Bbuildings = a.Bbuildings,
                            Bcolumns = a.Bcolumns,
                            Vid = b.Id,
                            Bsex = a.Bsex,
                            Earbugles = a.Earbugles,
                            Bheight = a.Bheight,
                            Blength = a.Blength,
                            Bust = a.Bust,
                            Bpipe = a.Bpipe,
                            Bscrotal = a.Bscrotal,
                            Bthickness = a.Bthickness,
                            Barea  = a.Barea,
                            Bwidth  = a.Bwidth,
                         }).ToList();
            if (!string.IsNullOrEmpty(Earbugles))
            {
                list = list.Where(x => x.Earbugles == Earbugles).ToList();
            }
            if (Vid != 0) 
            {
                list = list.Where(x => x.Vid == Vid).ToList();
            }
            return list.OrderByDescending(x => x.Id).ToList();

        }
        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BodySizeDTO> GetListAsync(int id)
        {
            var result = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Id == id);
            return ObjectMapper.Map<BodySize, BodySizeDTO>(result);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="bodySizeDTO"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<ResultDto<BodySizeDTO>> UpdateAsync(BodySizeDTO bodySizeDTO)
        {
                var result = await _weighInfoRepository.FindAsync(bodySizeDTO.Id);
                if (result == null)
                {
                    return new ResultDto<BodySizeDTO>() { Code = 500 };
                }
                ObjectMapper.Map(bodySizeDTO, result);
                var count = await _weighInfoRepository.UpdateAsync(result);
                var listCount=ObjectMapper.Map<BodySize, BodySizeDTO>(count);
                if (listCount != null)
                {
                    return new ResultDto<BodySizeDTO>() { Code = 200, Message = "修改成功" };
                }
                else
                {
                    return new ResultDto<BodySizeDTO>() { Code = 500, Message = "修改失败" };
                }

        }

        /// <summary>
        /// 体尺耳号下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<DropdownItemDto>> GetAppearEarbugles()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/earoverbit/earoverbits");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<EarOverbit>>(jsonString);
            // 查询已使用的数据的 Id 列表
            var usedDataIds = _weighInfoRepository.GetListAsync().Result.Select(d => d.Earbugles).ToList();
            var list = data.Where(d => !usedDataIds.Contains(d.OverbitName)).ToList();
            // 转换为 DropdownItemDto 并返回
            return list.Select(d => new DropdownItemDto { Id = d.Id, Name = d.OverbitName }).ToList();
        }


    }
}
